package com.mrjy.maintain.bo;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.mrjy.common.dto.QuestionCommentDto;
import com.mrjy.common.dto.UserSchoolRelDTO;
import com.mrjy.common.entity.IntegralExchange;
import com.mrjy.common.entity.IntegralExchangedLog;
import com.mrjy.common.entity.MessageInfo;
import com.mrjy.common.entity.PolyInfo;
import com.mrjy.common.entity.QuestionInfo;
import com.mrjy.common.entity.SchoolInfo;
import com.mrjy.common.entity.SchoolLinkageRel;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.entity.UserMemberInfo;
import com.mrjy.common.entity.UserSchoolRel;
import com.mrjy.common.entity.VideoType;
import com.mrjy.common.enums.ResultEnum;
import com.mrjy.common.util.DateUtil;
import com.mrjy.common.util.ExcelUtil;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.common.util.MD5Encrypt;
import com.mrjy.common.util.RedisUtil;
import com.mrjy.common.util.ResultUtil;
import com.mrjy.custom.dao.ICustomModuleDao;
import com.mrjy.custom.dto.CustomModuleDto;
import com.mrjy.integral.dao.IIntegralExchangeDao;
import com.mrjy.integral.dao.IIntegralExchangedLogDao;
import com.mrjy.integral.dto.IntegralExchangeDTO;
import com.mrjy.maintain.dao.ISchoolInfoDao;
import com.mrjy.maintain.dao.ISchoolLinkageRelDao;
import com.mrjy.maintain.dao.IServiceStationInfoDao;
import com.mrjy.maintain.dao.IUserInfoDao;
import com.mrjy.maintain.dao.IUserMemberInfoDao;
import com.mrjy.maintain.dao.IUserSchoolRelDao;
import com.mrjy.maintain.dto.SchoolInfoDTO;
import com.mrjy.maintain.util.RoleInfoEnum;
import com.mrjy.queries.dao.IQuestionCommentDao;
import com.mrjy.queries.dao.IQuestionInfoDao;
import com.mrjy.video.dao.IVideoTypeDao;
import com.mrjy.wechat.conts.WxConsts;

@Service("schoolInfoBo")
public class SchoolInfoBo implements ISchoolInfoBo{
	
	@Resource
	private ISchoolInfoDao schoolInfoDao;

	@Resource
	private IUserInfoDao userInfoDao;
	
	@Resource
	private ISchoolLinkageRelDao schoolLinkageRelDao;
	
	@Resource
	private IUserSchoolRelDao userSchoolRelDao;
	
	@Resource
	private IServiceStationInfoDao serviceStationInfoDao;
	
	@Resource
	private ICustomModuleDao customModuleDao;
	@Resource
	private IIntegralExchangeDao iIntegralExchangeDao;
	@Resource
	private IIntegralExchangedLogDao iIntegralExchangedLogDao;
	@Resource
	private IUserMemberInfoDao userMemberInfoDao;
	@Resource
	private IQuestionInfoDao questionInfoDao;
	@Resource
	private IVideoTypeDao videoTypeDao;
	@Resource
	private IQuestionCommentDao questionCommentDao;
	
	@Override
	public Map<String, Object> queryPage(SchoolInfoDTO dto) {
		Map<String, Object> map = new HashMap<String, Object>();
		//查询总数不变的合计
		SchoolInfoDTO paramDTO = new SchoolInfoDTO();
		int total = schoolInfoDao.countSchoolInfo(paramDTO);
		
		int pageTotal = schoolInfoDao.countSchoolInfo(dto);
		if(pageTotal > 0 ){
			List<SchoolInfoDTO> list = schoolInfoDao.queryPage(dto);
			if(list != null && list.size() > 0){
				map.put("err_code", 0);
				map.put("err_msg", "查询成功");
				map.put("rows", list);
                map.put("total", pageTotal);
                map.put("pageTotal", pageTotal);
			}else {
				map.put("err_code", 1);
				map.put("err_msg", "数据有问题");
				map.put("rows", list);
                map.put("total", pageTotal);
                map.put("pageTotal", pageTotal);
			}
		}else{
			map.put("err_code", 2);
			map.put("err_msg", "无数据");
			map.put("rows", null);
            map.put("total", pageTotal);
            map.put("pageTotal", 0);
		}
		return map;
	}
	

	@Override
	public Object txInsert(SchoolInfoDTO dto) {
		Map<String , Object> map = new HashMap<String, Object>();
		if(StringUtils.isBlank(dto.getSchoolName())){
			map.put("err_code", 101);
			map.put("err_msg", "学校名称为空");
			return map;
		}
		if(StringUtils.isBlank(dto.getCoverUrl())){
			map.put("err_code", 102);
			map.put("err_msg", "封面url为空");
			return map;
		}
		if(StringUtils.isBlank(dto.getLoginCode())){
			map.put("err_code", 103);
			map.put("err_msg", "管理员账号为空");
			return map;
		}
		UserInfo uuii = userInfoDao.queryByLoginCode(dto.getLoginCode());
		UserInfo adminUI = userInfoDao.queryByMobilePhone(dto.getMobilePhone());
		if(uuii != null ){
			if(adminUI != null && uuii.getId().intValue() != adminUI.getId().intValue()){
				map.put("err_code", 104);
				map.put("err_msg", "管理员账号已被使用，请重新输入");
				return map;
			}
		}
		
		if(StringUtils.isBlank(dto.getSignTimeStr())){
			map.put("err_code", 106);
			map.put("err_msg", "合同签订时间为空");
			return map;
		}
		if(null == dto.getContractYear()){
			map.put("err_code", 107);
			map.put("err_msg", "合同年限为空");
			return map;
		}
		if(StringUtils.isBlank(dto.getMobilePhone())){
			map.put("err_code", 108);
			map.put("err_msg", "手机号码为空");
			return map;
		}
		if ((StringUtils.isNotBlank(dto.getVoucherName())&&dto.getVoucherMoney()==null) 
			|| (dto.getVoucherMoney()!=null&&StringUtils.isBlank(dto.getVoucherName()))) 
			{
			map.put("err_code", 110);
			map.put("err_msg", "请完整填写补助券名称及金额");
			return map;
		}else if (null != dto.getVoucherMoney() && dto.getVoucherMoney()>365) {
			map.put("err_code", 111);
			map.put("err_msg", "补助券金额不得大于365元");
			return map;
		}
		Integer roleId = 0 ; //记录其输入手机号码现在所绑定的权限
		String recommendCode = ""; //推广码
		if(adminUI != null){
			if(adminUI.getRoleId() != null && adminUI.getRoleId().intValue() != RoleInfoEnum.SERVICE_ADMIN.getRoleId()
					&& adminUI.getRoleId().intValue() !=  RoleInfoEnum.STUDENT.getRoleId() 
					&& adminUI.getRoleId().intValue() != RoleInfoEnum.PARTNER_ADMIN.getRoleId()
					&& adminUI.getRoleId().intValue() != RoleInfoEnum.DISTRIBUTOR_ADMIN.getRoleId()){
				map.put("err_code", 109);
				map.put("err_msg", "该号码已绑定了其他角色用户，不能使用");
				return map;
			}else{
				roleId = adminUI.getRoleId();
				if(StringUtils.isNotBlank(adminUI.getRecommendCode())){
					recommendCode = adminUI.getRecommendCode();
				}
			}
		}
		//设置服务站推广码
		if(StringUtils.isBlank(recommendCode)){
	        recommendCode = userInfoDao.generateRecommendCodeOne(8);	
		}
		
		SchoolInfo info = new SchoolInfo();
		info.setSchoolName(dto.getSchoolName());
		info.setCreateTime(new Timestamp(System.currentTimeMillis()));
		info.setSignTime(dto.getSignTime());
		info.setContractYear(dto.getContractYear());
		info.setIsDiy(dto.getIsDiy());
		info.setSignTime(new Timestamp(DateUtil.stringToLong(dto.getSignTimeStr(), DateUtil.FULL_DATE)));
		if(info.getSignTime() != null && dto.getContractYear() != null){
			info.setDeadlineTime(new Timestamp(
					DateUtil.dateTimeAddYears(info.getSignTime().getTime(), dto.getContractYear())));
		}
		info.setDisableFlag(0);
		info.setCoverUrl(dto.getCoverUrl());
		info.setPromoteUrl(WxConsts.PUBLIC_DOMAIN + "/index.html?para=" + recommendCode);
		info.setInfoAuth(dto.getInfoAuth());
		if(StringUtils.isNotBlank(dto.getStudentGrade())){
			info.setStudentGrade(dto.getStudentGrade());
		}
		if(StringUtils.isNotBlank(dto.getStudentSchool())){
			info.setStudentSchool(dto.getStudentSchool());
		}
		if(StringUtils.isBlank(dto.getThreeLinkageFlag())){
			info.setThreeLinkageFlag("0");
		}else{
			info.setThreeLinkageFlag(dto.getThreeLinkageFlag());
		}
		if(StringUtils.isNotBlank(dto.getPullInfoAuth())){
			info.setPullInfoAuth(dto.getPullInfoAuth());
		}
		info.setMobilePhone(dto.getMobilePhone());
		info.setRegistType(dto.getRegistType());
		//如果学校自定义了diy，则视频目录音频目录必填
		if(dto.getIsDiy().equals(1)){
			if(null == dto.getCataid()){
				map.put("err_code", 112);
				map.put("err_msg", "视频存放目录不能为空");
				return map;
			}else{
				info.setCataid(dto.getCataid());
			}
			if(null== dto.getCatatree()){
				map.put("err_code", 113);
				map.put("err_msg", "音频存放目录不能为空");
				return map;
			}else{
				info.setCatatree(dto.getCatatree());
			}
		}
		//若开启政府补助券,则新增兑换物
		if (StringUtils.isNotBlank(dto.getVoucherName())) {
			IntegralExchangeDTO ie = new IntegralExchangeDTO();
			ie.setIeName(dto.getVoucherName());
			ie.setTypeId(2);
			ie.setScore(0);
			ie.setCreateTime(new Timestamp(System.currentTimeMillis()));
			ie.setDisableFlag(0);
			ie.setVoucherMoney(dto.getVoucherMoney());
			ie.setIsExpire(0);//未过期
			int roww = iIntegralExchangeDao.insert(ie);
			if (roww>0) {
				info.setVoucherId(ie.getId());
				info.setVoucherAuth("1");//0-未开启 1-已开启
			}
		}
		
		/*//插入标签表
		VideoType videoType = new VideoType();
		videoType.setCreateTime(new Timestamp(System.currentTimeMillis()));
		videoType.setTypeName(dto.getSchoolName());
		videoType.setDisableFlag(0);
		int rowww = videoTypeDao.insert(videoType);
		if (rowww>0) {
			info.setVideoTypeId(videoType.getId());
		}*/
		
		int count = schoolInfoDao.insert(info);
		if(count == 1){
			int row = 0 ;
			//插入成功后，插入管理员到用户表
			if(roleId == 0){//输入的手机号码可以用
				UserInfo ui = new UserInfo();
				ui.setSchoolId(info.getId());
				ui.setLoginCode(dto.getLoginCode());
				ui.setUserName(info.getSchoolName());
				ui.setPassword(MD5Encrypt.encryptByMD5(dto.getPasswordSrc()));
				ui.setDisableFlag(0);
				ui.setRecommendCode(recommendCode);
				ui.setRoleId(RoleInfoEnum.SCHOOL_ADMIN.getRoleId());
				ui.setRegisterDate(System.currentTimeMillis());
				ui.setMobilePhone(dto.getMobilePhone());
				
				row = userInfoDao.insert(ui);
			}else if(roleId.intValue() == RoleInfoEnum.STUDENT.getRoleId() 
					|| roleId.intValue() == RoleInfoEnum.SERVICE_ADMIN.getRoleId()
					|| roleId.intValue() == RoleInfoEnum.PARTNER_ADMIN.getRoleId()
					|| roleId.intValue() == RoleInfoEnum.DISTRIBUTOR_ADMIN.getRoleId()){//普通用户、服务站、合作方、分销商，直接修改权限
				adminUI.setSchoolId(info.getId());
				if(StringUtils.isBlank(adminUI.getLoginCode())){
					adminUI.setLoginCode(dto.getLoginCode());
				}
				if(StringUtils.isBlank(adminUI.getUserName())){
					adminUI.setUserName(info.getSchoolName());
				}
				if(adminUI.getPassword() == null ){
					adminUI.setPassword(MD5Encrypt.encryptByMD5(dto.getPasswordSrc()));
				}
				if(StringUtils.isBlank(adminUI.getRecommendCode())){
					adminUI.setRecommendCode(recommendCode);
				}
				if(roleId == RoleInfoEnum.STUDENT.getRoleId()){//普通用户-->学校管理员
					adminUI.setRoleId(RoleInfoEnum.SCHOOL_ADMIN.getRoleId());
				}else if(roleId == RoleInfoEnum.SERVICE_ADMIN.getRoleId()){//服务站-->服务站&学校管理员
					adminUI.setRoleId(RoleInfoEnum.SERVICE_SCHOOL_ADMIN.getRoleId());
				}else if(roleId == RoleInfoEnum.PARTNER_ADMIN.getRoleId()){//合作方-->合作方&学校管理员
					adminUI.setRoleId(RoleInfoEnum.PARTNER_SCHOOL_ADMIN.getRoleId());
				}else if(roleId == RoleInfoEnum.DISTRIBUTOR_ADMIN.getRoleId()){//分销商-->分销商&学校管理员
					adminUI.setRoleId(RoleInfoEnum.DISTRIBUTOR_SCHOOL_ADMIN.getRoleId());
				}
				row = userInfoDao.updateById(adminUI);
			}
			
			//操作3级联动子表
			if("1".equals(info.getThreeLinkageFlag())){//是三级联动
				List<SchoolLinkageRel> sLinkList = dto.getSLinkageList();
				if(sLinkList != null && sLinkList.size() > 0){
					for(SchoolLinkageRel rel : sLinkList){
						rel.setSchoolId(info.getId());
						rel.setCreateTime(new Timestamp(System.currentTimeMillis()));
						schoolLinkageRelDao.insert(rel);
					}
				}
			}
			
			if(row == 1){
				map.put("err_code", 0);
				map.put("err_msg", "插入成功");
			}else{
				map.put("err_code", 1);
				map.put("err_msg", "插入失败")	;
			}
			
		}else {
			map.put("err_code", 2);
			map.put("err_msg", "插入失败")	;
		}
		return map ;
		
	}
	@Override
	public Object queryById(Integer id) {
		Map<String,Object> map = new HashMap<String,Object>();
		if(id == null){
			map.put("err_code", -1);
			map.put("err_msg", "学校id为空");
			return map;
		}
		SchoolInfoDTO dto = schoolInfoDao.queryById(id);
		if(null != dto){
			List<Map<String,Object>> schoolList = null ;
			if("1".equals(dto.getThreeLinkageFlag())){
				List<SchoolLinkageRel> sLinkList = schoolLinkageRelDao.queryListBySchoolId(id);
				if(sLinkList != null && sLinkList.size() > 0){
					schoolList = new ArrayList<Map<String,Object>>();
					Map<String,Object> schoolMap =  null;
					for(SchoolLinkageRel rel : sLinkList){
						schoolMap =  new HashMap<String,Object>();
						schoolMap.put("school",rel.getStudentSchool() );
						if(StringUtils.isNotBlank(rel.getStudentGrade())){
							List<Map<String,String>> gradeList = new ArrayList<Map<String,String>>();
							String[] gradesArr = rel.getStudentGrade().split(";");
							for(String str : gradesArr){
								String[] arr = str.split("@_@");
								if(arr!=null && arr.length >0){
									Map<String,String> temp = new HashMap<String,String>();
									temp.put("grade", arr[0]);
									temp.put("class", arr[1]);
									
									gradeList.add(temp);
								}
							}
							schoolMap.put("grades", gradeList);
						}
						schoolList.add(schoolMap);
					}
				}
			}
			map.put("schoolLinkage", schoolList);
			map.put("err_code", 0);
			map.put("err_msg", "查询成功");
			map.put("info", dto);
		}else {
			map.put("err_code", 1);
			map.put("err_msg", "无数据");
			map.put("info", null);
		}
		return map;
	}
	@Override
	public Object txUpdateById(SchoolInfoDTO dto) {
		Map<String , Object> map = new HashMap<String, Object>();
		if(null == dto.getId()){
			map.put("err_code", 101);
			map.put("err_msg", "学校id为空");
			return map;
		}
		if(null == dto.getUserId()){
			map.put("err_code", 102);
			map.put("err_msg", "管理员id为空");
			return map;
		}
		if(StringUtils.isBlank(dto.getMobilePhone())){
			map.put("err_code", 103);
			map.put("err_msg", "手机号码为空");
			return map;
		}else{
			UserInfo ui = userInfoDao.queryByMobilePhone(dto.getMobilePhone());
			if(ui != null ){//不等于本来的id
				if(dto.getUserId().intValue() != ui.getId().intValue()){
					map.put("err_code", 104);
					map.put("err_msg", "该手机号码已经被绑定了!");
					return map;
				}
			}
		}
		if ((StringUtils.isNotBlank(dto.getVoucherName())&&dto.getVoucherMoney()==null) 
				|| (dto.getVoucherMoney()!=null&&StringUtils.isBlank(dto.getVoucherName()))) 
			{
			map.put("err_code", 110);
			map.put("err_msg", "请完整填写补助券名称及金额");
			return map;
		}else if (null!=dto.getVoucherMoney()&&dto.getVoucherMoney()>365) {
			map.put("err_code", 111);
			map.put("err_msg", "补助券金额不得大于365元");
			return map;
		}
		
		SchoolInfo info = new SchoolInfo();
		if(dto.getIsDiy().equals(1)){
			if(null == dto.getCataid()){
				map.put("err_code", 112);
				map.put("err_msg", "视频存放目录不能为空");
				return map;
			}else{
				info.setCataid(dto.getCataid());
			}
			if(null== dto.getCatatree()){
				map.put("err_code", 113);
				map.put("err_msg", "音频存放目录不能为空");
				return map;
			}else{
				info.setCatatree(dto.getCatatree());
			}
		}
		info.setId(dto.getId());
		info.setSchoolName(dto.getSchoolName());
		if(StringUtils.isNotBlank(dto.getSignTimeStr())){
			info.setSignTime(new Timestamp(DateUtil.stringToLong(dto.getSignTimeStr(), DateUtil.FULL_DATE)));
		}
		info.setContractYear(dto.getContractYear());
		if(info.getSignTime() != null && dto.getContractYear() != null){
			info.setDeadlineTime(new Timestamp(
					DateUtil.dateTimeAddYears(info.getSignTime().getTime(), dto.getContractYear())));
		}
		//info.setDisableFlag(0);
		info.setCoverUrl(dto.getCoverUrl());
		//info.setPromoteUrl(WxConsts.PUBLIC_DOMAIN + "/index.html?para=" + recommendCode);
		info.setInfoAuth(dto.getInfoAuth());
		
		info.setThreeLinkageFlag(dto.getThreeLinkageFlag());
		if("0".equals(dto.getThreeLinkageFlag())){
			info.setPullInfoAuth("");
			info.setStudentGrade("");
			info.setStudentSchool("");
		}else {
			info.setPullInfoAuth(dto.getPullInfoAuth());
			info.setStudentGrade(dto.getStudentGrade());
			info.setStudentSchool(dto.getStudentSchool());
		}
		
		info.setMobilePhone(dto.getMobilePhone());
		info.setRegistType(dto.getRegistType());
		info.setIsDiy(dto.getIsDiy());
		//新开启政府补助券(之前没有voucherId)-->新增兑换物
		SchoolInfoDTO school = schoolInfoDao.queryById(dto.getId());
		if (school.getVoucherId()==null) {
			if (StringUtils.isNotBlank(dto.getVoucherName())) {
				IntegralExchangeDTO ie = new IntegralExchangeDTO();
				ie.setIeName(dto.getVoucherName());
				ie.setTypeId(2);
				ie.setScore(0);
				ie.setCreateTime(new Timestamp(System.currentTimeMillis()));
				ie.setDisableFlag(0);
				ie.setVoucherMoney(dto.getVoucherMoney());
				ie.setIsExpire(0);//未过期
				int roww = iIntegralExchangeDao.insert(ie);
				if (roww>0) {
					info.setVoucherId(ie.getId());
					info.setVoucherAuth("1");//0-未开启 1-已开启
				}
			}
		}else {
			IntegralExchange ie = new IntegralExchange();
			if (StringUtils.isBlank(dto.getVoucherName())) {
				//相当于关闭补助券
				//禁用兑换物
				int[] ids = {school.getVoucherId()};
				ie.setIds(ids);
				ie.setDisableFlag(1);
				iIntegralExchangeDao.updateDisableFlag(ie);
				//学校信息的voucher_auth设为0(未开启政府补助券)
				info.setVoucherAuth("0");
			}else {
				//更新兑换物
				ie.setId(school.getVoucherId());
				ie.setIeName(dto.getVoucherName());
				ie.setVoucherMoney(dto.getVoucherMoney());
				iIntegralExchangeDao.updateById(ie);
			}
		}
		
		/*//更新标签表
		VideoType videoType = new VideoType();
		videoType.setId(school.getVideoTypeId());
		videoType.setTypeName(dto.getSchoolName());
		videoTypeDao.updateById(videoType);*/
		
		int count = schoolInfoDao.updateById(info);
		if(count == 1){
			//插入成功后，插入管理员到用户表
			
			UserInfo ui = new UserInfo();
			ui.setId(dto.getUserId());
			//ui.setSchoolId(info.getId());
			ui.setLoginCode(dto.getLoginCode());
			ui.setUserName(info.getSchoolName());
			ui.setMobilePhone(info.getMobilePhone());
			if(StringUtils.isNotBlank(dto.getPasswordSrc())){
				ui.setPassword(MD5Encrypt.encryptByMD5(dto.getPasswordSrc()));
			}
			int row = userInfoDao.updateById(ui);
			
			//根据schoolId 先删除之前的子表数据，再插入新的数据
			schoolLinkageRelDao.deleteBySchoolId(info.getId());
			//操作3级联动子表
			if("1".equals(info.getThreeLinkageFlag())){//是三级联动
				
				List<SchoolLinkageRel> sLinkList = dto.getSLinkageList();
				if(sLinkList != null && sLinkList.size() > 0){
					for(SchoolLinkageRel rel : sLinkList){
						rel.setSchoolId(info.getId());
						rel.setCreateTime(new Timestamp(System.currentTimeMillis()));
						schoolLinkageRelDao.insert(rel);
					}
				}
			}
			
			if(row == 1){
				map.put("err_code", 0);
				map.put("err_msg", "更新成功");
			}else{
				map.put("err_code", 1);
				map.put("err_msg", "更新失败")	;
			}
			
		}else {
			map.put("err_code", 2);
			map.put("err_msg", "更新失败")	;
		}
		return map ;
	}
	@Override
	public int deleteByIds(int[] ids) {
		try{
			return schoolInfoDao.deleteByIds(ids);
		}catch(DataAccessException  e){
			return 0;
		}
	}
	@Override
	public int txUpdateDisableFlag(SchoolInfo schoolInfo) {
		int []ids = schoolInfo.getIds();
		int count = schoolInfoDao.updateDisableFlag(schoolInfo);
		/*if(count > 0){
			for(int id : ids){
				UserInfo ui = userInfoDao.queryAdminBySchoolId(id);
				ui.setDisableFlag(schoolInfo.getDisableFlag());
				userInfoDao.updateById(ui);
			}
		}*/
		int[] arr = new int[ids.length];
		for (int i = 0;i<ids.length;i++) {
			SchoolInfoDTO school = schoolInfoDao.queryById(ids[i]);
			arr[i] = school.getVideoTypeId();
		}
		//操作标签
		VideoType videoType = new VideoType();
		videoType.setIds(arr);
		videoType.setDisableFlag(schoolInfo.getDisableFlag());
		videoTypeDao.updateDisableFlag(videoType);
		
		return count;
	}


	@Override
	public Object txQuerySchoolByRecommendCode(String recommendCode , Integer userId) {
		Map<String , Object> map = new HashMap<String, Object>();
		if(StringUtils.isBlank(recommendCode)){
			map.put("err_code", -1);
			map.put("err_msg", "传入参数为空");
			return map;
		}
		SchoolInfo info = schoolInfoDao.querySchoolByRecommendCode(recommendCode);
		if(info != null){
			//新增需求：   若最近一次扫的码是另一个新学校（可能是学校，也可能是服务站&学校），则所有弹框、文案、内容对应该新学校；
			if(userId != null){
				SchoolInfo old = schoolInfoDao.queryByUserId(userId);
				if(old != null && info.getId().intValue() != old.getId().intValue()){//不是同个学校
					UserSchoolRel param = new UserSchoolRel();
					param.setUserId(userId);
					param.setSchoolId(info.getId());
					UserSchoolRel rel = userSchoolRelDao.queryByUserIdAndSchoolId(param);
					if(rel != null){ //说明是有多条数据的，就把它的创时间修改成现在扫描的时间
						rel.setCreateTime(new Timestamp(System.currentTimeMillis()));
						userSchoolRelDao.updateById(rel);
					}
				}
			}
			map.put("err_code", 0);
			map.put("err_msg", "是合作的学校");
			map.put("info", info);
		}else {
			UserInfo station = userInfoDao.isStationByRecommendCode(recommendCode);
			//最近扫的码是服务站而不是升级学校功能的服务站，则清除之前所有的学校关联
			if(station != null && station.getRoleId().intValue() == RoleInfoEnum.SERVICE_ADMIN.getRoleId()){
				UserSchoolRel rel = new UserSchoolRel();
				rel.setUserId(userId);
				rel.setDisableFlag(1);
				userSchoolRelDao.updateByUserId(rel);
			}
			
			map.put("err_code", 1);
			map.put("err_msg", "不是合作的学校");
		}
		return map;
	}


	@Override
	public Object exportSchoolInfoBack(HttpServletResponse response ,SchoolInfoDTO dto) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<SchoolInfoDTO> list = schoolInfoDao.queryPage(dto);
		if (list.size()==0) {
			map.put("err_code", 404);
			map.put("err_msg", "无可导出数据");
			return map;
		}
		if(null != list && list.size() > 0){
			String fileName =  "校园信息" + DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR) + ".xls";
			try {
				ExcelUtil.writeExcel(response, fileName, list, SchoolInfoDTO.class);
				map.put("err_code", 200);
				map.put("err_msg", "导出成功");
			} catch (IllegalArgumentException | IllegalAccessException
					| IOException e) {
				e.printStackTrace();
				map.put("err_code", 500);
				map.put("err_msg", "导出失败");
			}
		}
		return map;
		
		
	}


	@Override
	public Map<String, Object> txCheckSchoolInfoStatusExpired() {
		Map<String,Object> map = new HashMap<String,Object>();
		List<SchoolInfoDTO> expireList = schoolInfoDao.checkSchoolInfoStatusExpired();
		if(expireList != null && expireList.size() > 0){
			SchoolInfo info = null;
			UserInfo ui = null ;
			int count = 0;
			for(SchoolInfoDTO dto : expireList){
				info = new SchoolInfo();
				info.setId(dto.getId());
				info.setDisableFlag(1);
				int num = schoolInfoDao.updateById(info);
				if(num == 1){
					ui = new UserInfo();
					ui.setId(dto.getUserId());
					ui.setDisableFlag(1);
					int row = userInfoDao.updateById(ui);
					if(row == 1){
						count ++ ;
					}
				}
			}
			if(count > 0){
				map.put("err_code", 0);
				map.put("err_msg", "成功更新了"+ count + "条学校信息");
			}else{
				map.put("err_code", 1);
				map.put("err_msg", "更新失败");
			}
		}else{
			map.put("err_code", 2);
			map.put("err_msg", "无过期数据");
		}
		
		return map;
	}


	@Override
	public Object checkRoleByMobilePhone(String mobilePhone) {
		Map<String,Object> map = new HashMap<String , Object>();
		if(StringUtils.isBlank(mobilePhone)){
			map.put("err_code", 100);
			map.put("err_msg", "手机号码为空");
			return map;
		}
		
		UserInfo ui = userInfoDao.queryByMobilePhone(mobilePhone);
		if(ui == null){
			map.put("err_code", 200);
			map.put("err_msg", "该号码可使用");
			return map;
		}
		if(ui.getRoleId() == null){
			map.put("err_code", 101);
			map.put("err_msg", "用户的权限为空");
			return map;
		}
		if(ui.getRoleId() != null 
				&& ui.getRoleId() != RoleInfoEnum.SERVICE_ADMIN.getRoleId() 
				&& ui.getRoleId() != RoleInfoEnum.STUDENT.getRoleId() 
				&& ui.getRoleId() != RoleInfoEnum.PARTNER_ADMIN.getRoleId()
				&& ui.getRoleId() != RoleInfoEnum.PARTNER_SCHOOL_ADMIN.getRoleId()){
			map.put("err_code", 102);
			map.put("err_msg", "该号码已绑定了其他角色用户，不能使用");
			return map;
		}
		if(ui.getRoleId() == RoleInfoEnum.SERVICE_ADMIN.getRoleId() 
				|| ui.getRoleId() == RoleInfoEnum.STUDENT.getRoleId()
				|| ui.getRoleId() == RoleInfoEnum.PARTNER_ADMIN.getRoleId()
				|| ui.getRoleId() == RoleInfoEnum.PARTNER_SCHOOL_ADMIN.getRoleId()){
			if(StringUtils.isBlank(ui.getLoginCode())){
				map.put("err_code", 201);
				map.put("err_msg", "该手机号码已注册，但没有账号密码");
				return map;
			}else{
				if(ui.getPassword() != null){
					map.put("err_code", 202);
					map.put("err_msg", "该手机号码已注册，且有账号密码");
					map.put("account", ui.getLoginCode());
					return map;
				}else{
					map.put("err_code", 203);
					map.put("err_msg", "该手机号码已注册，有账号没密码");
					map.put("account", ui.getLoginCode());
					return map;
				}
			}
		}
		
		return map;
	}


	@Override
	public Object drawSchool(SchoolInfoDTO dto,HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
        UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//        if (userInfo == null) {
//            map.put("err_code", -1);
//            map.put("err_msg", "当前用户未登录");
//            return map;
//        }
        if (StringUtils.isBlank(dto.getSortType())) {
        	map.put("err_code", 400);
        	map.put("err_msg", "参数异常");
        	return map;
		}
        if (null == dto.getId()) {
        	map.put("err_code", 400);
        	map.put("err_msg", "参数异常");
        	return map;
		}
        SchoolInfoDTO schoolInfo = schoolInfoDao.queryById(dto.getId());
        map.put("schoolInfo", schoolInfo);
        QuestionInfo questionInfo = new QuestionInfo();
//    	questionInfo.setTypeId(schoolInfo.getVideoTypeId());
//    	questionInfo.setGoodUserId(dto.getUserId());
//    	questionInfo.setQuestionTime(new Timestamp(System.currentTimeMillis()));
//    	//交流数
//        map.put("QAnum", questionInfoDao.countTopicPageByInfo(questionInfo));
        /*
         * 家长大学-免费课程
         */
        if (dto.getSortType().equals("free")) {
	        //判断用户是否已经领取补助券
	        IntegralExchangedLog log = new IntegralExchangedLog();
	        log.setUserId(dto.getUserId());
	        log.setIntegralExchangeId(schoolInfo.getVoucherId());
	        IntegralExchangedLog existVoucher = iIntegralExchangedLogDao.queryByUserIdAndIEId(log);
	        map.put("voucher", existVoucher==null?"notReceived":"hasReceived");
	        
	        //判断是否缴费
	        UserMemberInfo vip = userMemberInfoDao.selectIsVipByUserId(dto.getUserId());
	        map.put("payment", vip==null?"notPaid":"hasPaid");
	        
	        //判断是否报名(填写了孩子资料)
	        UserSchoolRel rel = new UserSchoolRel();
	        rel.setUserId(dto.getUserId());
	        rel.setSchoolId(dto.getId());
	        UserSchoolRel regist = userSchoolRelDao.queryByUserIdAndSchoolId(rel);
	        if (regist==null) {
	        	map.put("err_code", 401);
	        	map.put("err_msg", "用户不属于该学校");
	        	return map;
			}
	        map.put("regist", StringUtils.isBlank(regist.getStudentName())?"notRegist":"hasRegist");
        
        	CustomModuleDto module = new CustomModuleDto();
        	module.setCmType(2);//免费试听
        	module.setUserId(loginUser==null?null:loginUser.getId());
        	module.setPage(dto.getPage());
        	module.setRows(dto.getRows());
        	int total = customModuleDao.countPageCustomModule(module);
        	List<CustomModuleDto> list = null;
        	if (total>0) {
        		list = customModuleDao.queryPageCustomModule(module);
        		for (CustomModuleDto customModuleDto : list) {
					if (customModuleDto!=null) {
						PolyInfo polyInfo = RedisUtil.cache(customModuleDto.getCmProgramId()+"");
						customModuleDto.setIsVipStatus(RedisUtil.isVideoVip(dto.getId(), customModuleDto.getCmProgramId())?"1":"0");
						customModuleDto.setPolyInfo(polyInfo);
					}
				}
        	}
        	map.put("err_code", 200);
        	map.put("err_msg", "查询成功");
        	map.put("rows", list);
        	map.put("total", total);
		}
        /*
         * 家长大学-交流
         */
        else if (dto.getSortType().equals("communication")) {
        	questionInfo.setPage(dto.getPage());
        	questionInfo.setRows(dto.getRows());
        	List<QuestionCommentDto> list = questionInfoDao.queryTopicPageByInfo(questionInfo);
        	map.put("err_code", 200);
        	map.put("err_msg", "查询成功");
        	map.put("rows", list);
		}
        /*
         * 家长大学-明师支持
         */
        else if (dto.getSortType().equals("support")) {
        	UserInfo userInfo = new UserInfo();
        	userInfo.setPage(dto.getPage());
        	userInfo.setRows(dto.getRows());
        	List<UserInfo> list = userInfoDao.queryPageTeacherWithRecord(userInfo);
        	map.put("err_code", 200);
        	map.put("err_msg", "查询成功");
        	map.put("rows", list);
        }
		return map;
	}


	@Override
	public Object extrance(Integer schoolId, HttpSession session) {
		Map<String, Object> map = new HashMap<>();
		if (null == schoolId) {
			return ResultUtil.error(ResultEnum.PARAM_ERROR);
		}
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		UserSchoolRelDTO school = new UserSchoolRelDTO();
		int news = 0;
		//登录后才能看到学校入口
		if (null!=loginUser) {
			UserSchoolRel rel = new UserSchoolRel();
			rel.setUserId(loginUser.getId());
			rel.setSchoolId(schoolId);
			school = userSchoolRelDao.queryByUserId(rel);
			if (null!=school.getId()) {
				//家长大学的未读消息 （红色数字）
				MessageInfo msg = new MessageInfo();
				msg.setUserId(loginUser.getId());
				msg.setVideoTypeId(school.getVideoTypeId());
				int totalUnreadNum = questionCommentDao.queryTotalUnReadNumByCommentedId(msg);
				int totalUnreadGoodNum = questionCommentDao.queryTotalUnreadGoodNumByCommentedId(msg);
				news = totalUnreadGoodNum+totalUnreadNum;
			}
		}
		map.put("school", school.getStudentCount()==null||school.getStudentCount()==0?null:school);
		map.put("schoolNews", news);
		return ResultUtil.success(map);
  
	}


	@Override
	public Object querySchoolByid(Integer schoolId, HttpSession session) {
		// TODO Auto-generated method stub
		Map<String, Object> map = new HashMap<String, Object>();
        UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
        if (loginUser == null) {
            map.put("err_code", -1);
            map.put("err_msg", "当前用户未登录");
            return map;
        }
        SchoolInfoDTO schoolInfo = schoolInfoDao.queryById(schoolId);
        if(null != schoolInfo){
//        	QuestionInfo questionInfo = new QuestionInfo();
//        	questionInfo.setTypeId(schoolInfo.getVideoTypeId());
//        	questionInfo.setGoodUserId(loginUser.getId());
//        	questionInfo.setQuestionTime(new Timestamp(System.currentTimeMillis()));
//        	//交流数
//            map.put("QAnum", questionInfoDao.countTopicPageByInfo(questionInfo));
        	map.put("err_code", 200);
        	map.put("err_msg", "查询成功有数据");
        	map.put("schoolInfo", schoolInfo); 
        }else{
        	map.put("err_code", 200);
        	map.put("err_msg", "查询成功无数据");
        	map.put("schoolInfo", null);
        }
		return map;
	}


	@Override
	public Object countTopicPageByInfo(HttpSession session, Integer videoTypeId) {
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
        if (loginUser == null) {
            map.put("err_code", -1);
            map.put("err_msg", "当前用户未登录");
            return map;
        }
        
        QuestionInfo questionInfo = new QuestionInfo();
        questionInfo.setTypeId(videoTypeId);
    	questionInfo.setGoodUserId(loginUser.getId());
    	questionInfo.setQuestionTime(new Timestamp(System.currentTimeMillis()));
    	map.put("QAnum", questionInfoDao.countTopicPageByInfo(questionInfo));
    	map.put("err_code", 200);
    	map.put("err_msg", "查询成功有数据");
        
		return map;
	}
	
}
